package yannan.voiplock4ble;

import android.content.Intent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.Bind;
import butterknife.OnClick;
import yannan.voiplock4ble.base.Content;
import yannan.voiplock4ble.base.LoggedBaseActivity;
import yannan.voiplock4ble.base.MyApplication;
import yannan.voiplock4ble.bean.CheckFirVersion;
import yannan.voiplock4ble.bean.LockBean;
import yannan.voiplock4ble.eventbus.BaseEventMsg;
import yannan.voiplock4ble.eventbus.LockTimeMsg;
import yannan.voiplock4ble.eventbus.SetLockTimeMsg;
import yannan.voiplock4ble.net.NetUtils;
import yannan.voiplock4ble.net.base.NetworkCallBack;
import yannan.voiplock4ble.service.ble.BleService;
import yannan.voiplock4ble.service.ble.BleUtils;
import yannan.voiplock4ble.utils.TimeUtils;
import yannan.voiplock4ble.utils.ToastUtils;

/**
 * 门锁设置页面
 */
@Content(R.layout.activity_lock_setting)
public class LockSettingActivity extends LoggedBaseActivity {
    @Bind(R.id.btn_lock_update)
    TextView btnlockUpdate;
    @Bind(R.id.tv_lock_serial_num)
    TextView tvLockSerialNum;
    @Bind(R.id.tv_lock_time)
    TextView tvLockTime;
    @Bind(R.id.img_check_time)
    TextView imgCheckTime;
    @Bind(R.id.tv_current_time)
    TextView tvCurrentTime;
    @Bind(R.id.tv_vein_key)
    TextView tvVeinKey;
    @Bind(R.id.tv_pwd_key)
    TextView tvPwdKey;
    @Bind(R.id.tv_vein_admin)
    TextView tvVeinAdmin;
    @Bind(R.id.lock_update)
    LinearLayout lockUpdate;
    @Bind(R.id.tv_lock_ver_now)
    TextView tvLockVerNow;
    @Bind(R.id.tv_lock_ver_new)
    TextView tvLockVerNew;
    private LockBean lockBean;

    String url;

    @Override
    public void initData() {
//        MyApplication.getInterface().activityMap.put(this.getLocalClassName(), this);
        setTitleTheme(TitleTheme.TOOLBAR_THEME_COMMON, "门锁设置");
        lockUpdate.setVisibility(View.INVISIBLE);
        lockBean = (LockBean) getIntent().getSerializableExtra("lockBean");
        tvCurrentTime.setText("当前时间\n" + TimeUtils.getTimeHHmm());
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        MobclickAgent.onPageStart("LockSettingActivity");
        if (lockBean != null) {
            tvLockSerialNum.setText(lockBean.lockserialId);
            tvVeinKey.setText("指静脉钥匙开门：" + (lockBean.veinKeyState == 1 ? "已启用" : "未启用"));
            tvPwdKey.setText("密码钥匙开门：" + (lockBean.pwdKeyState == 1 ? "已启用" : "未启用"));
            if (MyApplication.getInterface().mConnectLock != null &&
                    MyApplication.getInterface().mConnectLock.lockserialId.equals(lockBean.lockserialId)
                    && MyApplication.getInterface().mConnectLock.contentToken != 0) {
                getLockInfo();
                tvLockVerNow.setText("门锁当前版本：" + MyApplication.getInterface().mConnectLock.firmwareVersion);
                checkVersion(MyApplication.getInterface().mConnectLock.firmwareVersion);
            } else {
                imgCheckTime.setText("门锁未连接");
                imgCheckTime.setBackgroundResource(R.drawable.button_checktime_circle_gray);
                imgCheckTime.setEnabled(false);
                tvLockVerNow.setText("门锁当前版本：");
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
        MobclickAgent.onPageEnd("LockSettingActivity");
    }

    /**
     * 检查版本
     *
     * @param firmwareVersion
     */
    private void checkVersion(final String firmwareVersion) {
        NetUtils.getNetworkService().checkFirVersion(lockBean.lockserialId)
                .enqueue(new NetworkCallBack<CheckFirVersion>() {
                    @Override
                    public void onSuc(CheckFirVersion resBody) {
                        // TODO: 2017/2/14 对比版本号
                        if (resBody.lockUrl != null) {
                            url = resBody.lockUrl;
                            tvLockVerNew.setText("门锁最新版本：" + resBody.lockVersion);
//                            if ((firmwareVersion.compareTo(resBody.lockVersion) < 0))
                                lockUpdate.setVisibility(View.VISIBLE);
                        }
                    }

                    @Override
                    public void onFail(String msg) {
                        //获取失败
                    }
                });
    }

    /**
     * 获取门锁信息
     */
    private void getLockInfo() {
        BleService.getBleService().sendOrder(BleUtils.getLockTime(MyApplication.getInterface().mConnectLock.contentToken));
    }

    @OnClick({R.id.btn_lock_update, R.id.img_check_time})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.btn_lock_update:
                Intent intent = new Intent(mContext, LockUpdateActivity.class);
                intent.putExtra("lockFirUrl", url);
                intent.putExtra("lockFirPkgType", 0);
                startActivity(intent);
                break;
            case R.id.img_check_time:
                //时间校准
                BleService.getBleService().sendOrder(
                        BleUtils.setLockTime(MyApplication.getInterface().mConnectLock.contentToken,
                                TimeUtils.getYear() - 2000,
                                TimeUtils.getMonth(),
                                TimeUtils.getDay(),
                                TimeUtils.getHour(),
                                TimeUtils.getMinute(),
                                TimeUtils.getSecond())
                );
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(BaseEventMsg msg) {
        if (msg instanceof LockTimeMsg) {
            LockTimeMsg lockTimeMsg = (LockTimeMsg) msg;
            String time = lockTimeMsg.time.substring(10, 16);
            tvLockTime.setText("门锁时间\n" + time);
        } else if (msg instanceof SetLockTimeMsg) {
            SetLockTimeMsg setLockTimeMsg = (SetLockTimeMsg) msg;
            if (setLockTimeMsg.isSuccess) {
                ToastUtils.showToast(mContext, "时间校准成功");
                getLockInfo();
            }
        }
    }
}
